package cn.minsh.lims.eoms.modules.app.service.impl;

import cn.minsh.lims.eoms.common.exception.RRException;
import cn.minsh.lims.eoms.common.utils.DateUtils;
import cn.minsh.lims.eoms.common.utils.ObjectToMapUtils;
import cn.minsh.lims.eoms.common.utils.PageUtils;
import cn.minsh.lims.eoms.common.utils.Query;
import cn.minsh.lims.eoms.modules.app.controller.req.*;
import cn.minsh.lims.eoms.modules.app.controller.req.wx.WxMaintenanceListReq;
import cn.minsh.lims.eoms.modules.app.controller.res.MaintenanceOrderInfoRes;
import cn.minsh.lims.eoms.modules.app.controller.res.MaintenanceOrderListRes;
import cn.minsh.lims.eoms.modules.app.controller.res.wx.WxMaintenanceOrderListRes;
import cn.minsh.lims.eoms.modules.app.dao.MaintenanceOrderDao;
import cn.minsh.lims.eoms.modules.app.entity.*;
import cn.minsh.lims.eoms.modules.app.enums.BusiTypeEnum;
import cn.minsh.lims.eoms.modules.app.enums.OrderStatusEnum;
import cn.minsh.lims.eoms.modules.app.message.MaintenanceOrderRejectMsg;
import cn.minsh.lims.eoms.modules.app.message.MaintenanceOrderRemindMsg;
import cn.minsh.lims.eoms.modules.app.message.MaintenanceOrderRequestCloseMsg;
import cn.minsh.lims.eoms.modules.app.service.*;
import cn.minsh.lims.eoms.modules.app.utils.CodeUtils;
import cn.minsh.lims.eoms.modules.app.utils.Constants;
import cn.minsh.lims.eoms.modules.app.utils.LocalDateUtils;
import cn.minsh.lims.eoms.modules.app.utils.StringConstants;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.*;
import java.util.stream.Collectors;

import static cn.minsh.lims.eoms.modules.app.utils.QueueUtils.*;


@Service("maintenanceOrderService")
public class MaintenanceOrderServiceImpl extends ServiceImpl<MaintenanceOrderDao, MaintenanceOrderEntity> implements MaintenanceOrderService {

    @Autowired
    private PlanScopeService planScopeService ;
    @Autowired
    private PlanContentService planContentService ;
    @Autowired
    private MaintenanceOrderRecordService orderRecordService ;
    @Autowired
    private PlanRemindService planRemindService ;
    @Autowired
    private QueueSendMessageService queueSendMessageService ;


    @Override
    public PageUtils queryPage(MaintenanceOrderListReq req,Long userId) {
        QueryWrapper<MaintenanceOrderEntity> queryWrapper = new QueryWrapper<>() ;
        if(req.getStatus()!=null) {
            queryWrapper.eq("status",req.getStatus()) ;
        }
        if (StringUtils.isNotBlank(req.getCode())){
            queryWrapper.like("code",req.getCode()) ;
        }
        if (StringUtils.isNotBlank(req.getName())){
            queryWrapper.like("name",req.getName()) ;
        }
        if (!CollectionUtils.isEmpty(req.getCreateByList())){
            queryWrapper.in("create_by",req.getCreateByList()) ;
        }
        if (!CollectionUtils.isEmpty(req.getAgentIdList())){
            queryWrapper.in("agent_id",req.getAgentIdList()) ;
        }
        if (StringUtils.isNotBlank(req.getOrder()) && StringUtils.isNotBlank(req.getSort())){
            queryWrapper.orderBy(StringUtils.isNotBlank(req.getOrder()) && StringUtils.isNotBlank(req.getSort()),"asc".equals(req.getSort()),req.getOrder()) ;
        }else{
            queryWrapper.orderByDesc("id") ;
        }
        queryWrapper.eq("is_del",0) ;


        IPage<MaintenanceOrderEntity> page = this.page(
                new Query<MaintenanceOrderEntity>().getPage(ObjectToMapUtils.setConditionMap(req)),
                queryWrapper
        );

        IPage<MaintenanceOrderListRes> retPage = new Page<>(page.getCurrent(),page.getSize()) ;
        retPage.setPages(page.getPages()) ;
        retPage.setTotal(page.getTotal()) ;

        List<MaintenanceOrderListRes> resList = new ArrayList<>() ;
        //处理业务
        if (!CollectionUtils.isEmpty(page.getRecords())){
            page.getRecords().stream().forEach(e->{
                MaintenanceOrderListRes res = new MaintenanceOrderListRes() ;
                BeanUtils.copyProperties(e,res);
                resList.add(res) ;
            });
        }

        retPage.setRecords(resList) ;

        return new PageUtils(retPage);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void saveOrder(MaintenanceOrderReq req,Long userId) {
        //1、添加保养工单
        MaintenanceOrderEntity orderEntity = new MaintenanceOrderEntity() ;
        BeanUtils.copyProperties(req,orderEntity);
        orderEntity.setCreateBy(userId) ;
        orderEntity.setCreateTime(new Date());
        orderEntity.setUpdateBy(userId) ;
        orderEntity.setUpdateTime(new Date());
        orderEntity.setCode(CodeUtils.getCode(Constants.MAINTENANCE_CODE_BEGIN_WITH,Constants.CODE_LEN));
        this.save(orderEntity) ;
        //2、添加保养范围
        if (!CollectionUtils.isEmpty(req.getScopeIdList())) {
            List<PlanScopeEntity> planScopeEntityList = new ArrayList<>() ;
            req.getScopeIdList().forEach(e->{
                PlanScopeEntity planScopeEntity = new PlanScopeEntity() ;
                planScopeEntity.setType(BusiTypeEnum.MAINTENANCEORDER.getCode());
                planScopeEntity.setPlanId(orderEntity.getId());
                planScopeEntity.setScopeId(e);
                planScopeEntity.setIsDel(0);
                planScopeEntityList.add(planScopeEntity) ;
            });
            planScopeService.saveBatch(planScopeEntityList) ;
        }
        //3、添加提醒时间
        List<PlanRemindEntity> remindEntityList = new ArrayList<>() ;
        req.getRemindList().stream().forEach(e->{
            PlanRemindEntity remindEntity = new PlanRemindEntity() ;
            remindEntity.setType(BusiTypeEnum.MAINTENANCEORDER.getCode());
            remindEntity.setLeadTime(e);
            remindEntity.setIsDel(0);
            remindEntity.setPlanId(orderEntity.getId());
            remindEntityList.add(remindEntity) ;
        });
        planRemindService.saveBatch(remindEntityList) ;

        //4、添加保养内容
        if (!CollectionUtils.isEmpty(req.getContentList())){
            List<PlanContentEntity> planContentEntityList = new ArrayList<>() ;
            req.getContentList().stream().forEach(e->{
                PlanContentEntity entity = new PlanContentEntity() ;
                entity.setPlanId(orderEntity.getId());
                entity.setType(BusiTypeEnum.MAINTENANCEORDER.getCode());
                entity.setContent(e);
                entity.setIsDel(0);
                planContentEntityList.add(entity) ;
            });
            planContentService.saveBatch(planContentEntityList) ;
        }
        //5、添加保养工单记录
        MaintenanceOrderRecordEntity orderRecordEntity = new MaintenanceOrderRecordEntity() ;
        orderRecordEntity.setMaintenanceOrderId(orderEntity.getId());
        orderRecordEntity.setOperatorId(userId);
        orderRecordEntity.setOperatorTime(new Date());
        orderRecordEntity.setOperation("发起工单");
        orderRecordEntity.setExplain("经办人为："+req.getAgentId());
        orderRecordService.save(orderRecordEntity) ;
        //TODO 推送消息,提醒
        /**
         * "标题：新工单提醒
         * 提醒内容：
         * 您有一条新的工单提醒
         * 工单编号：20180413
         * 工单类型：保养工单
         * 工单时间：2018-9-26（工单发起时间）
         * 工单详情：经办人完成工单，请提关闭"
         */
        MaintenanceOrderRemindMsg msg = new MaintenanceOrderRemindMsg() ;
        msg.setTitle("新工单提醒");
        msg.setContent("您有一条新的工单提醒");
        msg.setReceiver(req.getAgentId()+"");
        msg.setOrderCode(orderEntity.getCode());
        msg.setOrderTime(DateUtils.format(orderEntity.getCreateTime(),DateUtils.DATE_PATTERN));
        msg.setDetail("经办人完成工单，请提关闭");

        /*
        msg.setCode(orderEntity.getCode());
        msg.setMaintenanceOrderTime(LocalDateUtils.format(orderEntity.getMaintenanceTime(),LocalDateUtils.DATE_PATTERN));
        //查询保养范围
        List<PlanScopeEntity> scopeList= planScopeService.listByTypeAndPlanId(BusiTypeEnum.MAINTENANCEORDER.getCode(),orderEntity.getId()) ;
        if (!CollectionUtils.isEmpty(scopeList)){
            msg.setScopeIdList(scopeList.stream().map(PlanScopeEntity::getScopeId).collect(Collectors.toList()));
        }*/
        queueSendMessageService.sendMessage(MAINTENANCE_ORDER_ADD,msg) ;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void updateOrderById(MaintenanceOrderReq req,Long userId) {
        Long orderAgentId = null ;
        MaintenanceOrderEntity orderEntity = this.getById(req.getId()) ;
        if (Objects.isNull(orderEntity)||orderEntity.getId()==null){
            throw new RRException("保养工单不存在") ;
        }
        //1、修改工单，仅未开始的功能可以修改
        //1.1、只有未开始的订单可以修改
        if (!OrderStatusEnum.NOT_STARTED.getCode().equals(orderEntity.getStatus())){
            throw new RRException("只有未开始的订单可以修改") ;
        }
        orderAgentId = orderEntity.getAgentId() ;
        orderEntity.setName(req.getName());
        orderEntity.setLevel(req.getLevel());
        orderEntity.setType(req.getType());
        orderEntity.setSupplierId(req.getSupplierId());
        orderEntity.setMaintenanceTime(req.getMaintenanceTime());
        orderEntity.setAgentId(req.getAgentId());
        orderEntity.setUpdateBy(userId);
        orderEntity.setUpdateTime(new Date());
        this.updateById(orderEntity) ;

        //2、修改保养范围
        //2.1、删除保养范围
        planScopeService.deleteByPlanId(BusiTypeEnum.MAINTENANCEORDER.getCode(), req.getId());
        //2.2、批量添加保养范围
        List<PlanScopeEntity> planScopeEntityList = new ArrayList<>() ;
        req.getScopeIdList().stream().forEach(e->{
            PlanScopeEntity scopeEntity = new PlanScopeEntity() ;
            scopeEntity.setType(BusiTypeEnum.MAINTENANCEORDER.getCode());
            scopeEntity.setPlanId(req.getId());
            scopeEntity.setScopeId(e);
            scopeEntity.setIsDel(0);
            planScopeEntityList.add(scopeEntity) ;
        });
        planScopeService.saveBatch(planScopeEntityList) ;
        //3、修改提醒时间
        //3.1、删除提醒时间
        planRemindService.deleteByPlanId(BusiTypeEnum.MAINTENANCEORDER.getCode(),req.getId()) ;
        //3.2、添加提醒时间
        List<PlanRemindEntity> remindEntityList = new ArrayList<>() ;
        if (!CollectionUtils.isEmpty(req.getRemindList())) {
            req.getRemindList().stream().forEach(e -> {
                PlanRemindEntity remindEntity = new PlanRemindEntity();
                remindEntity.setType(BusiTypeEnum.MAINTENANCEORDER.getCode());
                remindEntity.setLeadTime(e);
                remindEntity.setIsDel(0);
                remindEntity.setPlanId(orderEntity.getId());
                remindEntityList.add(remindEntity);
            });
            planRemindService.saveBatch(remindEntityList);
        }
        //4、修改保养内容
        //4.1、删除保养内容
        planContentService.deleteByPlanId(BusiTypeEnum.MAINTENANCEORDER.getCode(),req.getId());
        //4.2、添加保养内容
        if (!CollectionUtils.isEmpty(req.getContentList())){
            List<PlanContentEntity> planContentEntityList = new ArrayList<>() ;
            req.getContentList().stream().forEach(e->{
                PlanContentEntity entity = new PlanContentEntity() ;
                entity.setPlanId(orderEntity.getId());
                entity.setType(BusiTypeEnum.MAINTENANCEORDER.getCode());
                entity.setContent(e);
                entity.setIsDel(0);
                planContentEntityList.add(entity) ;
            });
            planContentService.saveBatch(planContentEntityList) ;
        }
        //5、添加保养工单记录
        String operator = null ;
        String explain = null ;
        if (req.getAgentId().equals(orderAgentId)) {
            operator = "修改保养工单" ;
            explain = "修改保养工单" ;
        }else{
            operator = "修改经办人" ;
            explain = "修改工单经办人为："+req.getAgentId() ;
        }
        MaintenanceOrderRecordEntity orderRecordEntity = new MaintenanceOrderRecordEntity() ;
        orderRecordEntity.setMaintenanceOrderId(orderEntity.getId());
        orderRecordEntity.setOperatorId(userId);
        orderRecordEntity.setOperatorTime(new Date());
        orderRecordEntity.setOperation(operator);
        orderRecordEntity.setExplain(explain);
        orderRecordService.save(orderRecordEntity) ;


        if (!req.getAgentId().equals(orderAgentId)) {
            /**
             * "标题：新工单提醒
             * 提醒内容：
             * 您有一条新的工单提醒
             * 工单编号：20180413
             * 工单类型：保养工单
             * 工单时间：2018-9-26（工单发起时间）
             * 工单详情：经办人完成工单，请提关闭"
             */
            //TODO 添加推送消息提醒
            MaintenanceOrderRemindMsg msg = new MaintenanceOrderRemindMsg() ;
            msg.setTitle("新工单提醒");
            msg.setContent("您有一条新的工单提醒");
            msg.setReceiver(req.getAgentId()+"");
            msg.setOrderCode(orderEntity.getCode());
            msg.setOrderTime(DateUtils.format(orderEntity.getCreateTime(),DateUtils.DATE_PATTERN));
            msg.setDetail("经办人完成工单，请提关闭");

            /*msg.setCode(orderEntity.getCode());
            msg.setMaintenanceOrderTime(LocalDateUtils.format(orderEntity.getMaintenanceTime(),LocalDateUtils.DATE_PATTERN));
            //查询保养范围
            List<PlanScopeEntity> scopeList= planScopeService.listByTypeAndPlanId(BusiTypeEnum.MAINTENANCEORDER.getCode(),req.getId()) ;
            if (!CollectionUtils.isEmpty(scopeList)){
                msg.setScopeIdList(scopeList.stream().map(PlanScopeEntity::getScopeId).collect(Collectors.toList()));
            }*/
            queueSendMessageService.sendMessage(MAINTENANCE_ORDER_ADD,msg) ;
        }
    }

    @Override
    public MaintenanceOrderInfoRes queryById(Long id,Long userId) {
        MaintenanceOrderInfoRes res = new MaintenanceOrderInfoRes() ;
        //查询详情
        MaintenanceOrderEntity orderEntity = this.getById(id) ;
        if (Objects.isNull(orderEntity) && orderEntity.getId()==null){
            throw new RRException("订单记录不存在") ;
        }
        BeanUtils.copyProperties(orderEntity,res) ;
        //查询范围
        List<PlanScopeEntity> planScopeEntityList = planScopeService.listByTypeAndPlanId(BusiTypeEnum.MAINTENANCEORDER.getCode(),id) ;
        if (!CollectionUtils.isEmpty(planScopeEntityList)){
            res.setScopeList(planScopeEntityList.stream().map(PlanScopeEntity::getScopeId).collect(Collectors.toList()));
        }
        //查询内容
        List<PlanContentEntity> planContentEntityList = planContentService.listByTypeAndPlanId(BusiTypeEnum.MAINTENANCEORDER.getCode(),id) ;
        if (!CollectionUtils.isEmpty(planContentEntityList)){
            res.setContentList(planContentEntityList.stream().map(PlanContentEntity::getContent).collect(Collectors.toList()));
        }
        //查询提醒
        List<PlanRemindEntity> planRemindEntityList = planRemindService.listByTypeAndPlanId(BusiTypeEnum.MAINTENANCEORDER.getCode(),id) ;
        if (!CollectionUtils.isEmpty(planRemindEntityList)){
            res.setRemindList(planRemindEntityList.stream().map(PlanRemindEntity::getLeadTime).collect(Collectors.toList()));
        }
        res.setLoginUserId(userId);
        res.setRecordResList(analysisList(userId,orderEntity));
        return res ;
    }



    private List<MaintenanceOrderInfoRes.RecordRes>  analysisList(Long userId,MaintenanceOrderEntity orderEntity){
        //判断当前登录人是发起人，发起人可以看到所有日志
        List<MaintenanceOrderRecordEntity> recordList = orderRecordService.listByMaintenanceId(orderEntity.getId())  ;
        List<MaintenanceOrderInfoRes.RecordRes> recordResList = new ArrayList<>() ;
        if (userId.equals(orderEntity.getCreateBy())){
            if (!CollectionUtils.isEmpty(recordList)){
                recordList.stream().forEach(e->{
                    MaintenanceOrderInfoRes.RecordRes recordRes = new MaintenanceOrderInfoRes.RecordRes() ;
                    BeanUtils.copyProperties(e,recordRes);
                    recordRes.setUserId(StringConstants.analysisExplain(recordRes.getOperation(),recordRes.getExplain()));
                    recordRes.setExplain(StringConstants.analysisExplain(recordRes.getExplain(),recordRes.getUserId()));
                    recordResList.add(recordRes) ;
                });
            }
        }else{
            //非当前人只能看到自己的操作记录
            if (!CollectionUtils.isEmpty(recordList)){
                recordList.stream().forEach(e->{
                    if("关闭工单".equals(e.getOperation())){// 关闭当前人的工单)
                        //如果为关闭工单，需要查看上一条记录是否当事人，是的情况隐藏维修总结,否则不可见
                        if (!CollectionUtils.isEmpty(recordResList)){
                            MaintenanceOrderInfoRes.RecordRes tempRecord = recordResList.get(recordResList.size()-1) ;
                            if (userId.equals(tempRecord.getOperatorId())){//上一条操作记录是当前登录人
                                MaintenanceOrderInfoRes.RecordRes recordRes = new MaintenanceOrderInfoRes.RecordRes();
                                BeanUtils.copyProperties(e, recordRes) ;
                                if(recordRes.getExplain() != null && recordRes.getExplain().contains(";维修总结：")){
                                    recordRes.setExplain(recordRes.getExplain().substring(0,recordRes.getExplain().indexOf(";维修总结：")));
                                }
                                recordRes.setUserId(StringConstants.analysisExplain(recordRes.getOperation(),recordRes.getExplain()));
                                recordRes.setExplain(StringConstants.analysisExplain(recordRes.getExplain(),recordRes.getUserId()));
                                recordResList.add(recordRes) ;
                            }
                        }
                    }else {
                        Long tempUserId = StringConstants.analysisExplain(e.getOperation(),e.getExplain()) ;
                        if (tempUserId.equals(userId) //指向给当前人
                                ||e.getOperatorId().equals(userId) //当前人操作
                        ){
                            MaintenanceOrderInfoRes.RecordRes recordRes = new MaintenanceOrderInfoRes.RecordRes() ;
                            BeanUtils.copyProperties(e,recordRes);
                            recordRes.setUserId(tempUserId);
                            recordRes.setExplain(StringConstants.analysisExplain(recordRes.getExplain(),tempUserId));
                            recordResList.add(recordRes) ;
                        }
                    }
                });
            }
        }

        if (!CollectionUtils.isEmpty(recordResList)) {
            Collections.reverse(recordResList);
        }
        return recordResList ;
    }



    @Override
    public void accept(AcceptOrderReq req,Long userId) {
        //1判断订单是否存在
        MaintenanceOrderEntity orderEntity = this.getById(req.getId()) ;
        if (orderEntity == null || orderEntity.getId()==null){
            throw new RRException("记录不存在") ;
        }
        if(!userId.equals(orderEntity.getAgentId())){
            throw new RRException("当前的登录人非经办人" );
        }
        /*//2、判断订单状态
        if (!OrderStatusEnum.NOT_STARTED.getCode().equals(orderEntity.getStatus())){
            throw new RRException("非未开始状态不能接受") ;
        }*/
        /*if (OrderStatusEnum.NOT_STARTED.getCode().equals(orderEntity.getStatus())){
            //如果未开始直接开始
            orderEntity.setStatus(OrderStatusEnum.STARTED.getCode());
        }*/
        orderEntity.setStatus(OrderStatusEnum.STARTED.getCode());
        orderEntity.setPlanFixTime(DateUtils.stringToDate(req.getPlanDate(),DateUtils.DATE_PATTERN));
        orderEntity.setUpdateBy(userId);
        orderEntity.setUpdateTime(new Date());
        this.updateById(orderEntity) ;
        //3、添加日志
        //添加日志记录
        MaintenanceOrderRecordEntity orderRecordEntity = new MaintenanceOrderRecordEntity() ;

        orderRecordEntity.setOperatorId(userId);
        orderRecordEntity.setOperatorTime(new Date());
        orderRecordEntity.setMaintenanceOrderId(req.getId());
        orderRecordEntity.setOperation("接受工单");
        orderRecordEntity.setExplain("计划保养时间："+req.getPlanDate());
        orderRecordService.save(orderRecordEntity) ;

    }

    @Override
    public void reject(RejectOrderReq req,Long userId) {
        //1判断订单是否存在
        MaintenanceOrderEntity orderEntity = this.getById(req.getId()) ;
        if (orderEntity == null || orderEntity.getId()==null){
            throw new RRException("记录不存在") ;
        }
        if(!userId.equals(orderEntity.getAgentId())){
            throw new RRException("当前的登录人非经办人" );
        }
        //2、判断订单状态
        /*if (!OrderStatusEnum.NOT_STARTED.getCode().equals(orderEntity.getStatus())){
            throw new RRException("非未开始状态不能接受") ;
        }*/
        //未开始订单直接拒绝
        /*if (OrderStatusEnum.NOT_STARTED.getCode().equals(orderEntity.getStatus())){
            orderEntity.setStatus(OrderStatusEnum.REJECT.getCode());
        }*/
        orderEntity.setStatus(OrderStatusEnum.REJECT.getCode()) ;
        orderEntity.setUpdateBy(userId);
        orderEntity.setUpdateTime(new Date());
        //修改经办人
        orderEntity.setAgentId(orderEntity.getCreateBy());
        this.updateById(orderEntity) ;
        //3、添加日志
        MaintenanceOrderRecordEntity orderRecordEntity = new MaintenanceOrderRecordEntity() ;
        orderRecordEntity.setOperatorId(userId);
        orderRecordEntity.setOperatorTime(new Date());
        orderRecordEntity.setMaintenanceOrderId(req.getId());
        orderRecordEntity.setOperation("拒绝工单");
        orderRecordEntity.setExplain("拒绝原因："+req.getReason());
        orderRecordService.save(orderRecordEntity) ;

        /**
         * "标题：新工单提醒
         * 提醒内容：
         * 您有一条新的工单提醒
         * 工单编号：20180413
         * 工单类型：保养工单
         * 工单时间：2018-9-26（工单发起时间）
         * 工单详情：经办人拒绝接受工单，请至后台进行处理"
         */
        //TODO 保养工单被拒绝
        MaintenanceOrderRejectMsg msg = new MaintenanceOrderRejectMsg() ;
        msg.setTitle("保养工单提醒");
        msg.setContent("你有一个保养工单被拒绝，请及时处理");
        msg.setReceiver(orderEntity.getCreateBy()+"");
        msg.setOrderCode(orderEntity.getCode());
        msg.setOrderTime(DateUtils.format(orderEntity.getCreateTime(),DateUtils.DATE_PATTERN));
        msg.setDetail("经办人拒绝接受工单，请至后台进行处理");

        /*
        msg.setCode(orderEntity.getCode());
        msg.setMaintenanceOrderTime(LocalDateUtils.format(orderEntity.getMaintenanceTime(),LocalDateUtils.DATE_PATTERN));

        msg.setReason(req.getReason());
        //查询保养范围
        List<PlanScopeEntity> scopeList= planScopeService.listByTypeAndPlanId(BusiTypeEnum.MAINTENANCEORDER.getCode(),req.getId()) ;
        if (!CollectionUtils.isEmpty(scopeList)){
            msg.setScopeIdList(scopeList.stream().map(PlanScopeEntity::getScopeId).collect(Collectors.toList()));
        }*/
        queueSendMessageService.sendMessage(MAINTENANCE_ORDER_REJECT,msg);

    }

    @Override
    public void updateAgent(ModifyAgentOrderReq req,Long userId) {
        //修改经办人
        MaintenanceOrderEntity orderEntity = this.getById(req.getId()) ;
        if (Objects.isNull(orderEntity)||orderEntity.getId()==null){
            throw new RRException("记录不存在") ;
        }
        if(!userId.equals(orderEntity.getCreateBy())){
            throw new RRException("当前的登录人非发起人" );
        }
        //未开始、已完成、已拒绝状态，报修人可修改经办人
        if (!(OrderStatusEnum.NOT_STARTED.getCode().equals(orderEntity.getStatus())
                ||OrderStatusEnum.COMPLETE.getCode().equals(orderEntity.getStatus())
                ||OrderStatusEnum.REJECT.getCode().equals(orderEntity.getStatus()))){
            throw new RRException("未开始、已完成、已拒绝状态可修改经办人") ;
        }

        //修改
        orderEntity.setAgentId(req.getAgentId());
        orderEntity.setStatus(OrderStatusEnum.NOT_STARTED.getCode());
        orderEntity.setUpdateBy(userId);
        orderEntity.setUpdateTime(new Date());
        this.updateById(orderEntity) ;

        //添加记录
        MaintenanceOrderRecordEntity orderRecordEntity = new MaintenanceOrderRecordEntity() ;

        orderRecordEntity.setOperatorId(userId);
        orderRecordEntity.setOperatorTime(new Date());
        orderRecordEntity.setMaintenanceOrderId(req.getId());
        orderRecordEntity.setOperation("修改经办人");
        orderRecordEntity.setExplain("修改工单经办人为："+req.getAgentId());
        orderRecordService.save(orderRecordEntity) ;
        //TODO 发送消息，通过经办人
        /**
         * "标题：新工单提醒
         * 提醒内容：
         * 您有一条新的工单提醒
         * 工单编号：20180413
         * 工单类型：保养工单
         * 工单时间：2018-9-26（工单发起时间）
         * 工单详情：经办人完成工单，请提关闭"
         */
        MaintenanceOrderRemindMsg msg = new MaintenanceOrderRemindMsg() ;
        msg.setTitle("新工单提醒");
        msg.setContent("您有一条新的工单提醒");
        msg.setReceiver(req.getAgentId()+"");
        msg.setOrderCode(orderEntity.getCode());
        msg.setOrderTime(DateUtils.format(orderEntity.getCreateTime(),DateUtils.DATE_PATTERN));
        msg.setDetail("经办人完成工单，请提关闭");

        /*
        msg.setCode(orderEntity.getCode());
        msg.setMaintenanceOrderTime(LocalDateUtils.format(orderEntity.getMaintenanceTime(),LocalDateUtils.DATE_PATTERN));
        //查询保养范围
        List<PlanScopeEntity> scopeList= planScopeService.listByTypeAndPlanId(BusiTypeEnum.MAINTENANCEORDER.getCode(),req.getId()) ;
        if (!CollectionUtils.isEmpty(scopeList)){
            msg.setScopeIdList(scopeList.stream().map(PlanScopeEntity::getScopeId).collect(Collectors.toList()));
        }*/
        queueSendMessageService.sendMessage(MAINTENANCE_ORDER_ADD,msg) ;

    }

    @Override
    public void uploadResult(MaintenanceResultReq req,Long userId) {
        //修改订单状态
        MaintenanceOrderEntity orderEntity = this.getById(req.getId()) ;
        if (Objects.isNull(orderEntity)||orderEntity.getId()==null){
            throw new RRException("记录不存在") ;
        }
        if(!userId.equals(orderEntity.getAgentId())){
            throw new RRException("当前的登录人非经办人" );
        }
        //TODO 是否限制处理中的订单能完成??
        orderEntity.setStatus(OrderStatusEnum.COMPLETE.getCode());
        orderEntity.setUpdateBy(userId);
        orderEntity.setUpdateTime(new Date());
        orderEntity.setCompleteTime(req.getCompleteTime());
        //修改经办人
        orderEntity.setAgentId(orderEntity.getCreateBy());
        this.updateById(orderEntity) ;

        //添加日志
        MaintenanceOrderRecordEntity orderRecordEntity = new MaintenanceOrderRecordEntity() ;

        orderRecordEntity.setOperatorId(userId);
        orderRecordEntity.setOperatorTime(new Date());
        orderRecordEntity.setMaintenanceOrderId(req.getId());
        orderRecordEntity.setOperation("提交保养结果");
        orderRecordEntity.setExplain("保养完成时间："+ LocalDateUtils.format(req.getCompleteTime(),LocalDateUtils.DATE_PATTERN)
                +";保养结果说明："+req.getExplain());
        orderRecordService.save(orderRecordEntity) ;

        //TODO 推送消息,给发起人推送消息
        /**
         * "标题：新工单提醒
         * 提醒内容：
         * 您有一条新的工单提醒
         * 工单编号：20180413
         * 工单类型：保养工单
         * 工单时间：2018-9-26（工单发起时间）
         * 工单详情：经办人完成工单，请提关闭，请至后台进行处理"
         */
        MaintenanceOrderRequestCloseMsg msg = new MaintenanceOrderRequestCloseMsg() ;
        msg.setTitle("保养工单提醒");
        msg.setContent("你有一个保养工单请提关闭，请及时处理");
        msg.setReceiver(orderEntity.getCreateBy()+"");
        msg.setOrderCode(orderEntity.getCode());
        msg.setOrderTime(DateUtils.format(orderEntity.getCreateTime(),DateUtils.DATE_PATTERN));
        msg.setDetail("经办人完成工单，请提关闭，请至后台进行处理");

        /*
        msg.setCode(orderEntity.getCode());
        msg.setMaintenanceOrderTime(LocalDateUtils.format(orderEntity.getMaintenanceTime(),LocalDateUtils.DATE_PATTERN));

        msg.setCompleteTimeStr(LocalDateUtils.format(req.getCompleteTime(),LocalDateUtils.DATE_TIME_MINUTE_PATTERN));
        //查询保养范围
        List<PlanScopeEntity> scopeList= planScopeService.listByTypeAndPlanId(BusiTypeEnum.MAINTENANCEORDER.getCode(),req.getId()) ;
        if (!CollectionUtils.isEmpty(scopeList)){
            msg.setScopeIdList(scopeList.stream().map(PlanScopeEntity::getScopeId).collect(Collectors.toList()));
        }*/
        queueSendMessageService.sendMessage(MAINTENANCE_ORDER_COMPLETE,msg);

    }

    @Override
    public void closeOrder(MaintenanceOrderCloseReq req,Long userId) {
        //修改订单状态
        MaintenanceOrderEntity orderEntity = this.getById(req.getId()) ;
        if (Objects.isNull(orderEntity)||orderEntity.getId()==null){
            throw new RRException("记录不存在") ;
        }

        if(!userId.equals(orderEntity.getCreateBy())){
            throw new RRException("当前的登录人非发起人" );
        }
        orderEntity.setStatus(OrderStatusEnum.CLOSE.getCode());
        orderEntity.setUpdateBy(userId);
        orderEntity.setUpdateTime(new Date());
        this.updateById(orderEntity) ;

        //添加日志
        MaintenanceOrderRecordEntity orderRecordEntity = new MaintenanceOrderRecordEntity() ;

        orderRecordEntity.setOperatorId(userId);
        orderRecordEntity.setOperatorTime(new Date());
        orderRecordEntity.setMaintenanceOrderId(req.getId());
        orderRecordEntity.setOperation("工单关闭");
        orderRecordEntity.setExplain("保养总结："+req.getSummary());
        orderRecordService.save(orderRecordEntity) ;
    }

    @Override
    public PageUtils queryWxPage(WxMaintenanceListReq req,Long userId) {
        QueryWrapper<MaintenanceOrderEntity> queryWrapper = new QueryWrapper<>() ;
        List<WxMaintenanceOrderListRes> resList = new ArrayList<>() ;
        IPage<WxMaintenanceOrderListRes> retPage = null ;

        List<Integer> statusList = new ArrayList<>() ;
        statusList.add(OrderStatusEnum.NOT_STARTED.getCode()) ;
        statusList.add(OrderStatusEnum.STARTED.getCode()) ;
        queryWrapper.eq("is_del",0) ;
        //已处理，参与过的
        if (req.getOrderType()==2){

            //可能参与多次，取最新一次，去重
            List<MaintenanceOrderRecordEntity> orderRecordEntityList = orderRecordService.listRepeatByUserId(userId) ;
            List<Long> orderIdList = new ArrayList<>() ;
            if (CollectionUtils.isEmpty(orderRecordEntityList)){
                //不存在记录，直接返回
                retPage = new Page<>(req.getPage(),req.getLimit()) ;
            }else {
                orderIdList = orderRecordEntityList.stream().map(MaintenanceOrderRecordEntity::getMaintenanceOrderId).collect(Collectors.toList());
                //已处理
                queryWrapper.in("id",orderIdList) ;
                //queryWrapper.ne("agent_id",userId) ;

                //queryWrapper.notIn("status",statusList) ;
                queryWrapper.and(wrapper->wrapper.or(p->p.in("status",statusList).ne("agent_id",userId)).or(pp->pp.notIn("status",statusList))) ;

                queryWrapper.orderByDesc("update_time") ;
                
                IPage<MaintenanceOrderEntity> page = this.page(
                        new Query<MaintenanceOrderEntity>().getPage(ObjectToMapUtils.setConditionMap(req)),
                        queryWrapper
                );

                retPage = new Page<>(page.getCurrent(),page.getSize()) ;
                retPage.setPages(page.getPages()) ;
                retPage.setTotal(page.getTotal()) ;
                //处理业务
                if (!CollectionUtils.isEmpty(page.getRecords())){
                    page.getRecords().stream().forEach(e->{
                        WxMaintenanceOrderListRes res = new WxMaintenanceOrderListRes() ;
                        BeanUtils.copyProperties(e,res);
                        //处理已处理时间，经办人操作时间,此处记录肯定存在，不用判空处理
                        res.setUpdateTime(orderRecordEntityList.stream().filter(p->(p.getMaintenanceOrderId().equals(e.getId())) && p.getOperatorId().equals(userId)).map(MaintenanceOrderRecordEntity::getOperatorTime).collect(Collectors.toList()).get(0));
                        resList.add(res) ;
                    });
                }
                retPage.setRecords(resList) ;
            }
            return new PageUtils(retPage);

        }else{
            //待处理
            //待处理列表,本人待处理工单，未开始，处理中的订单，最后一次分配倒序，及update_time 倒序
            queryWrapper.eq("agent_id",userId) ;
            queryWrapper.in("status",statusList) ;
            queryWrapper.orderByDesc("update_time") ;
            IPage<MaintenanceOrderEntity> page = this.page(
                    new Query<MaintenanceOrderEntity>().getPage(ObjectToMapUtils.setConditionMap(req)),
                    queryWrapper
            );

            retPage = new Page<>(page.getCurrent(),page.getSize()) ;
            retPage.setPages(page.getPages()) ;
            retPage.setTotal(page.getTotal()) ;
            //处理业务
            if (!CollectionUtils.isEmpty(page.getRecords())){
                page.getRecords().stream().forEach(e->{
                    WxMaintenanceOrderListRes res = new WxMaintenanceOrderListRes() ;
                    BeanUtils.copyProperties(e,res);
                    resList.add(res) ;
                });
            }

            retPage.setRecords(resList) ;
            return new PageUtils(retPage);
        }
    }
}